package com.hud.easynavi;

import android.util.Log;

import java.nio.ByteBuffer;

import protocol.CircularByteBuffer;

public class SerialPortMsgParser
{
    final static String TAG = "[SerialPortParser]:";
    public interface OnFilterResultListener{
        void OnMessageReceive(ByteBuffer dataBuf);
    }
    OnFilterResultListener listener;
    boolean ready = false;
    CircularByteBuffer cbuf;

    int msgLen = 0;
    int headIndex = -1;
    byte[] frameBuf = null;

    public SerialPortMsgParser() {
        cbuf = new CircularByteBuffer(4 * 1024);
    }

    void d(String msg)
    {
        Log.d(TAG,msg);
    }

    public void onDataFiltering(byte[] data, int len)
    {
        cbuf.WriteArray(data, len);
        while ((headIndex = cbuf.IndexOf((byte)0x55, (byte)0xaa)) != -1)
        {
            msgLen = cbuf.getInt32(headIndex, 2) + 6;
            if (msgLen > cbuf.ReadableBytes())// 断包
            {
                break;
            }
            byte[] _frame_data = new byte[msgLen];
            cbuf.ReadArray(msgLen,_frame_data);
            ByteBuffer bb = ByteBuffer.wrap(_frame_data);
            if(listener!=null){
                listener.OnMessageReceive(bb);
            }
        }
    }

    public void setLisenter(OnFilterResultListener lis){
        listener = lis;
    }

    public void reset()
    {
    }
}
